import { getTemplatRemote } from '@/api/template'
import _ from 'lodash'
import remote from './props'

export default {
  data () {
    return {
      // remote 弹窗
      remoteShow: false,

      // 远程输入位置
      isRemotePosition: false,
    }
  },

  mixins: [remote],

  computed: {
    // 是否远程
    isRemote () {
      return this.remote && this.remoteUrl && this.inputValue
    },
  },

  methods: {
    // onBlur
    onBlur () {
      if (!this.isRemote) return false
      let mesg = ''
      const index = _
        .findIndex(this.remoteList, (v) => v === this.inputValue)
      if (index === -1) {
        mesg = '请输入正确信息！'
        this.resetValue()
      }
      this.errorMessage = mesg
    },

    // 远程数据
    getRemote: _.debounce(
      function remote () {
        getTemplatRemote(this.remoteUrl, { inputValue: this.inputValue, fid: this.id })
          .then((data = []) => {
            this.remoteList = data
            this.remoteShow = (data.length > 0)
          })
      }, 120,
    ),

    // 远程数据设置
    setRemoteValue (val) {
      this.remoteShow = false
      this.toggleEvent('input', val)
      this.validate()
    },

    // handleClickOutside
    handleClickOutside () {
      this.remoteShow = false
    },

    // 设备边界
    getClientRect () {
      return this.$refs.customForm.offsetTop
    },

    // event input
    onInput (val) {
      this.toggleEvent('input', val)

      this.validate()
        .then(() => {
          this.isRemote && this.getRemote()
        })
        .catch(() => {
          this.remoteShow = false
        })
    },
  },
}
